﻿using Newtonsoft.Json;
using QH.JobBack.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace JobBack.Models
{
    public class CookieUtils
    {
        public static string SYSTEMLOGINCOOKIEKEY = "SYSTEMLOGINCOOKIEKEY";
        /// <summary>
        /// 取得Cookie登录信息
        /// </summary>
        public static UserData GetLoginCookieInfo()
        {
            UserData ret = null; ;
            var cookie = HttpContext.Current.Request.Cookies[SYSTEMLOGINCOOKIEKEY];
            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                try
                {
                    var ticket = FormsAuthentication.Decrypt(cookie.Value);
                    ret = (UserData)JsonConvert.DeserializeObject(ticket != null ? ticket.UserData : "", typeof(UserData));
                }
                catch
                {

                }
            }
            return ret;
        }

        /// <summary>
        /// 保存用户登录cookie信息
        /// </summary>
        /// <param name="userData"></param>
        public static void SaveLoginCookieInfo(UserData userData)
        {
            var json = JsonConvert.SerializeObject(userData, Formatting.None,
                      new JsonSerializerSettings()
                      {
                          ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                      });

            //创建一个凭据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userData.AdminName, DateTime.Now, DateTime.Now.AddMinutes(60), false, json);
            //数据加密
            string enyTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(SYSTEMLOGINCOOKIEKEY, enyTicket);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 移除用户授权的cookie
        /// </summary>
        /// <param name="principal"></param>
        public static void RemoveAuthCookie(UTPrincipal principal)
        {
            HttpCookie removeCookie;
            string cookieName;
            int limit = HttpContext.Current.Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {
                cookieName = HttpContext.Current.Request.Cookies[i].Name;
                if (cookieName == SYSTEMLOGINCOOKIEKEY) continue;
                if (!cookieName.Equals(FormsAuthentication.FormsCookieName, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                removeCookie = new HttpCookie(cookieName);
                removeCookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(removeCookie);
            }
            if (principal != null)
            {
                // FuncCodeMapStore.Remove(principal.Identity.userid);
            }
            HttpContext.Current.Session.Abandon();
        }

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="loginname">用户名</param>
        /// <param name="userData">用户数据</param>
        /// <param name="rememberMe">记住</param>
        public static HttpCookie SetAuthCookie(string loginname, UserData  role, bool rememberMe)
        {
            if (role == null)
            {
                throw new ArgumentNullException("userData");
            }
            string _userdata = JsonConvert.SerializeObject(role, Formatting.None,
                        new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });

            //创建ticket
            var ticket = new FormsAuthenticationTicket(
                1, loginname, DateTime.Now, DateTime.Now.AddDays(1), rememberMe, _userdata);

            //加密ticket
            var cookieValue = FormsAuthentication.Encrypt(ticket);

            //创建Cookie
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
            {
                HttpOnly = true,
                Domain = FormsAuthentication.CookieDomain,
                Path = FormsAuthentication.FormsCookiePath
            };
            if (rememberMe)
                cookie.Expires = DateTime.Now.AddDays(1);

            //写入Cookie
            HttpContext.Current.Response.Cookies.Remove(cookie.Name);
            HttpContext.Current.Response.Cookies.Add(cookie);

            //  Medicom.Common.Log.Info(loginname + " 登录");
            var user = HttpContext.Current.User;
            return cookie;
        }

        /// <summary>
        /// 解析身份认证信息
        /// </summary>
        /// <param name="request">http请求对象</param>
        /// <returns>身份认证信息</returns>
        public static UTPrincipal TryParsePrincipal(HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            try
            {
                var cookie = request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie == null)
                {
                    return null;
                }

                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                if (ticket != null)
                {
                    UTPrincipal myPrincipal = new UTPrincipal(ticket);
                    return new UTPrincipal(ticket);
                }
            }
            catch (Exception e)
            {
                // Medicom.Common.Log.Error("解析登录信息错误：", e);
            }
            return null;
        }
    }
}